import 'package:FineArt/core/api/module_api.dart';
import 'package:FineArt/core/utils/event.dart';
import 'package:FineArt/core/widget/tab_indicator.dart';
import 'package:FineArt/page/home/module_page.dart';
import 'package:FineArt/page/home/module_staggered_grid_page.dart';
import 'package:FineArt/page/search/searchmain.dart';
import 'package:FineArt/page/tab/recommend/recommendmain.dart';
import 'package:FineArt/utils/image_utils.dart';
import 'package:FineArt/utils/log_util.dart';
import 'package:FineArt/utils/size_config.dart';
import 'package:badges/badges.dart';
import 'package:event_bus/event_bus.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../constants.dart';

import 'dart:ui' as ui;
import 'package:FineArt/page/my/noticelist.dart';
import 'module_video_grid_page.dart';

class TabHomePage extends StatefulWidget {
  List<Module> modules = [];

  TabHomePage(this.modules);

  @override
  _TabHomePageState createState() => _TabHomePageState();
}

class _TabHomePageState extends State<TabHomePage>
    with SingleTickerProviderStateMixin {
  ui.Image tabIndicatorImg = null;
  List<Text> module_texts = [];
  List<Module> modules = [];
  List<Widget> module_pages = [];
  final double module_font_size_selected = 18;
  final double module_font_size_unselected = 16;

  int current_module_idx = 0;
  int currentTabIndex = 0;

  void _initTab() {
    // bool hasVideo=false;
    // for (Module module in widget.modules) {
    //   if(module.section=="视频"){
    //     hasVideo =true;
    //     break;
    //   }
    // }
    // if(!hasVideo){
    //   Module mv=Module(section: "视频",id: 6,mode: 0);
    //   LogUtil.d("no video start  added by client========>>>>>>>>>>>>>....");
    //   widget.modules.add(mv);
    // }
    tabController = TabController(
        initialIndex: currentTabIndex,
        length: widget.modules.length + 1,
        vsync: this); //+1 is for ’推荐‘
    // 添加监听器
    tabController.addListener(() => _onTabChanged());
    double w = getPortraitSWidth(21);

    // ImageUtils.getUiImage("assets/images/tab_indicator1.png", 10, 23)
    //     .then((image) {
    //   setState(() {
    //     tabIndicatorImg = image;
    //   });
    // });

    // ImageUtils.getSvgImageFromString(context,"assets/images/tab_indicator3.svg")
    //     .then((image) {
    //   setState(() {
    //     tabIndicatorImg = image;
    //   });
    // });

    module_texts.clear();
    current_module_idx = 0;
    module_texts
        .add(Text("推荐", style: TextStyle(fontSize: module_font_size_selected)));
    for (Module module in widget.modules) {
      module_texts.add(Text(module.section,
          style: TextStyle(fontSize: module_font_size_unselected)));
    }

    modules.clear();
    modules.addAll(widget.modules);

    module_pages.clear();
    module_pages.add(RecommendMainPage(
      modules: widget.modules,
    ));

    for (Module module in widget.modules) {
      // module_pages.add(ModulePage(module));
      if (module.section == "视频") {
        module_pages.add(ModuleVideoPage(module));
      } else
        module_pages.add(ModuleStaggeredPage(module));
    }
  }

  void searchClick() {
    Navigator.of(context).push(MaterialPageRoute(builder: (context) {
      return SearchMainPage();
    }));
  }

  var _eventBusListener;

  @override
  void initState() {
    super.initState();
    _initTab();
    _eventBusListener = XEvent.on("tabIndex", (index) {
      LogUtil.d("_eventBus>> $index");
      setState(() {
        tabController.index = index;
        _tabClick(index);
      });
    });
  }

  _tabClick(index) {
    current_module_idx = index;
    module_texts.clear();
    module_texts.add(Text("推荐",
        style: TextStyle(
            fontSize: index == 0
                ? module_font_size_selected
                : module_font_size_unselected)));
    for (int i = 0; i < widget.modules.length; i++) {
      Module module = widget.modules[i];
      if (index == i + 1) {
        module_texts.add(Text(module.section,
            style: TextStyle(fontSize: setSp(module_font_size_selected))));
      } else {
        module_texts.add(Text(module.section,
            style: TextStyle(fontSize: setSp(module_font_size_unselected))));
      }
    }
  }

// 点击监听函数
  _onTabChanged() {
    LogUtil.d("tabchange>>" + tabController.index.toString());
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        elevation: 0,
        toolbarHeight: getPortraitSHeight(80),
        backgroundColor: Colors.white,
        brightness: Brightness.light,
        automaticallyImplyLeading: false,
        leadingWidth: 0,
        titleSpacing: 0,
        title: Container(
          width: SizeConfig.screenWidth,
          margin: EdgeInsets.symmetric(horizontal: getPortraitSWidth(12)),
          // height: 100,
          child: Row(
            children: [
              InkWell(
                onTap: (){
                  Navigator.of(context).push(MaterialPageRoute(builder: (context){
                    return NoticeListPage();
                  }));
                },
                child: Badge(
                  badgeContent: Text(
                    '',
                    style: TextStyle(color: Colors.white, fontSize: setSp(10)),
                  ),
                  child: Image.asset(
                    "assets/images/icon_message.png",
                    width: getPortraitSWidth(30),
                    height: getPortraitSHeight(22),
                  ),
                ),
              ),
              // ),
              SizedBox(width: getPortraitSWidth(16)),
              GestureDetector(
                onTap: searchClick,
                child: Container(
                  height: getPortraitSHeight(33),
                  margin: EdgeInsets.symmetric(vertical: 8),
                  padding: EdgeInsets.symmetric(horizontal: 20, vertical: 1),
                  width:
                      MediaQuery.of(context).size.width - getPortraitSWidth(70),
                  decoration: BoxDecoration(
                    color: bg_input,
                    borderRadius: BorderRadius.circular(29),
                  ),
                  child: Row(
                    children: [
                      Image.asset(
                        "assets/images/icon_search.png",
                        width: getPortraitSWidth(17),
                        height: getPortraitSHeight(17),
                      ),
                      Text(
                        "搜索内容",
                        style: TextStyle(
                            color: text_input_hint_color, fontSize: setSp(13)),
                      )
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
        bottom: _buildTabBar(),
      ),
      body: Padding(
        padding: const EdgeInsets.only(top: 8, left: 4, right: 4),
        child: TabBarView(
          physics: NeverScrollableScrollPhysics(), //disable swipe
          children: module_pages,
          controller: tabController,
        ),
      ),
    );
  }

  TabController tabController;
  TabBar _tabBar;

  Widget _buildTabBar() {
    _tabBar = TabBar(
      onTap: (index) {
        _tabClick(index);
      },
      controller: tabController,
      tabs: module_texts,
      labelColor: text_black,
      labelStyle: TextStyle(fontWeight: FontWeight.bold),
      unselectedLabelColor: Color.fromARGB(0xff, 0x78, 0x78, 0x78),
      unselectedLabelStyle: TextStyle(fontWeight: FontWeight.bold),
      indicatorSize: TabBarIndicatorSize.label,
      indicator: TabIndicator(null),
      // indicator: BoxDecoration(
      //   image: DecorationImage(
      //     image: AssetImage("assets/images/tab_indicator1.png"),
      //     fit: BoxFit.scaleDown,
      //     scale: 0.5
      //   ),
      // ),
      labelPadding: EdgeInsets.symmetric(horizontal: 0),
      isScrollable: false, //是否可滑动，设置不可滑动，则是tab的宽度等长
    );
    return _tabBar;
  }

  @override
  void dispose() {
    tabController.dispose();
    XEvent.cancel("tabIndex", _eventBusListener);
    super.dispose();
  }
}
